<template>
  <el-form ref="formRef" :model="password" :rules="rules" :label-width="200">
    <el-form-item :label="t('profile.password.oldPassword')" prop="oldPassword">
      <InputPassword v-model="password.oldPassword" />
    </el-form-item>
    <el-form-item :label="t('profile.password.newPassword')" prop="newPassword">
      <InputPassword v-model="password.newPassword" strength />
    </el-form-item>
    <el-form-item :label="t('profile.password.confirmPassword')" prop="confirmPassword">
      <InputPassword v-model="password.confirmPassword" strength />
    </el-form-item>
    <el-form-item>
      <XButton :title="t('common.save')" type="primary" @click="submit(formRef)" />
      <XButton :title="t('common.reset')" type="danger" @click="reset(formRef)" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'

import { InputPassword } from '@/components/InputPassword'
import { updateUserPassword } from '@/api/system/user/profile'
import * as ConfigApi from '@/api/system/config'

defineOptions({ name: 'ResetPwd' })

const { t } = useI18n()
const message = useMessage()
const formRef = ref<FormInstance>()
const password = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRule = ref({
  includeDigits: true,
  includeLetters: true,
  includeSpecialChars: true,
  length: 10
})

const validatePassword = (rule: any, value: any, callback: any) => {
  if (rule.fullField == 'confirmPassword' || rule.field == 'confirmPassword') {
    if (!value) {
      callback('请输入确认密码')
    }
    if (value !== password.newPassword) {
      callback(new Error(t('profile.password.diffPwd')))
    } else {
      callback()
    }
  } else {
    !value && callback('请输入新密码')
  }
  // 构建正则表达式，根据校验规则生成对应的正则模式
  let pattern = '^'
  if (passwordRule.value?.includeDigits) pattern += '(?=.*[0-9])' // 包含数字
  if (passwordRule.value?.includeLetters) pattern += '(?=.*[a-zA-Z])' // 包含字母
  if (passwordRule.value?.includeSpecialChars) pattern += '(?=.*[!@#$%^&+=])' // 包含特殊字符，你也可以根据具体需要调整特殊字符的范围
  pattern += `.{${passwordRule.value?.length},}$` // 最小长度

  // 创建正则表达式对象
  const regex = new RegExp(pattern)
  // 进行校验
  if (!regex.test(value)) {
    const digits = passwordRule.value?.includeDigits ? '数字，' : ''
    const letters = passwordRule.value?.includeLetters ? '字母，' : ''
    const specialChars = passwordRule.value?.includeSpecialChars ? '特殊字符（!@#$%^&*），' : ''
    const lengthLimit = passwordRule.value?.length ? `最小长度为${passwordRule.value.length}` : ''
    const needAnd = (digits || letters || specialChars) && lengthLimit ? '以及' : ''
    const warning = `必须含${digits + letters + specialChars + needAnd + lengthLimit}`
    callback(new Error(warning))
  } else {
    callback()
  }
}
const getConfig = async () => {
  const data = await ConfigApi.clientGet()
  const complexities = data.passwordComplexity.split(',').map(Number)
  passwordRule.value = {
    includeDigits: complexities.indexOf(1) !== -1,
    includeLetters: complexities.indexOf(2) !== -1,
    includeSpecialChars: complexities.indexOf(3) !== -1,
    length: data.minLength
  }
}
// 表单校验
const equalToPassword = (_rule, value, callback) => {
  if (password.newPassword !== value) {
    callback(new Error(t('profile.password.diffPwd')))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: t('profile.password.oldPwdMsg'), trigger: 'blur' },
    { min: 6, max: 20, message: t('profile.password.pwdRules'), trigger: 'blur' }
  ],
  newPassword: [{ validator: validatePassword, required: true, trigger: 'blur' }],
  confirmPassword: [{ validator: validatePassword, required: true, trigger: 'blur' }]
})

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await updateUserPassword(password.oldPassword, password.newPassword)
      message.success(t('common.updateSuccess'))
    }
  })
}

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  getConfig()
})
</script>
